<template>
  <div style="margin: 10px 0;height: 87vh">
    <!-- 头部操作内容 -->
    <div>
      <div>
        <div v-role="'超级管理员'" style="margin:10px 0;display: inline-block">
          <el-radio-group v-model="page.lookMe" @input="getPage">
            <el-radio :label=true>只看我自己</el-radio>
            <el-radio :label=false>查看所有人的模板</el-radio>
          </el-radio-group>
        </div>
        <div style="margin:5px 0">
          <el-input size="mini" style="width: 200px" v-model="page.name" placeholder="根据模板名称模糊搜索" clearable></el-input>
          <el-input size="mini" style="width: 200px;margin-left: 5px" v-model="page.adId" placeholder="根据管理员ID精确搜素" clearable></el-input>
          <el-button style="margin-left: 5px" size="mini" type="primary" @click="getPage">搜索</el-button>
          <el-button style="margin-left: 5px" size="mini" type="info" @click="clearPageConditions">清空</el-button>
        </div>
      </div>
      <el-button
          type="info"
          size="mini"
          style="display: inline-block;font-size: 15px"
          @click="emptyEditingTask();drawer=true"
      >
        添加新的模板
      </el-button>


    </div>

    <!-- 表格以及相关内容 -->
    <div style="margin: 10px 0">
      <el-table
          :stripe=true
          :border=true
          :data="page.data"
          style="width: 100%"
          v-loading="page.loading"
          :height="'70vh'"
      >
        <el-table-column
            align="center"
            prop="name"
            label="模板名称"
        >
        </el-table-column>

        <el-table-column
            align="center"
            prop="id"
            label="模板编号"
            width="100"
        >
        </el-table-column>

        <el-table-column
            align="center"
            prop="adId"
            label="所属用户编号"
            width="120"
        >
        </el-table-column>

        <el-table-column
            align="center"
            prop="createTime"
            label="创建时间"
            width="180"
        >
        </el-table-column>

        <el-table-column
            align="center"
            prop="updateTime"
            label="修改时间"
            width="180"
        >
        </el-table-column>

        <el-table-column
            align="center"
            label="操作"
            width="200"
        >
          <template slot-scope="scope">
            <el-button
                style="border: none;"
                type="primary"
                icon="el-icon-edit"
                circle
                plain
                @click="drawer=true;templateAddToEditTask(scope.row)"
            >
            </el-button>
            <el-button
                style="border: none;"
                type="success"
                icon="el-icon-copy-document"
                circle
                plain
                @click="openCopyTaskTemplateDiaLog(scope.row)"
            >
            </el-button>

            <el-popconfirm
                style="margin-left:5px;"
                confirm-button-text='好的'
                cancel-button-text='不用了'
                icon="el-icon-info"
                icon-color="red"
                title="这是一段内容确定删除吗？"
                @confirm="removeTemplate(scope.row.id)"
            >
              <el-button
                  style="border: none;"
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  plain
              >
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: center;margin-top: 20px">
        <el-pagination
            background
            :page-sizes="[10, 30, 50, 100]"
            :page-size="page.size"
            layout='prev, pager, next, jumper,->, sizes,total'
            :total="page.total"
            :page-count="page.pages"
            :current-page="page.current"
            @size-change="pageChange"
            @current-change="currentChange"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 遮罩相关内容 -->
    <div>
      <el-drawer
          style="overflow: hidden !important;"
          direction="ltr"
          title="编辑模板"
          :visible.sync="drawer"
          size="50%">
        <div slot="title" style="text-align:center">
          <span style="font-size: 25px;font-weight: bold;color: #576574;letter-spacing: 0.1em">编辑模板</span>
        </div>
        <el-container style="margin: 10px;">
          <el-header>
            <div style="margin-bottom: 10px;">
              <el-tooltip effect="dark" content="模板名称" placement="top-end">
                <el-input
                    v-model="sTemplateName"
                    style="width:85%"
                    placeholder="请输入模板名称"
                >
                </el-input>
              </el-tooltip>

              <el-button
                  @click="commitTemplate()"
                  style="float: right"
                  type="primary"
                  plain
              >
                提交该模板
              </el-button>
            </div>

            <div style="margin-bottom: 10px;">
              <el-tooltip effect="dark" content="选择需要添加的任务" placement="top-end">
                <el-select
                    style="float: left;width: 85%"
                    v-model="sTaskId"
                    filterable
                    placeholder="请选择任务"
                >
                  <el-option
                      v-for="item in robotTaskList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-tooltip>

              <el-button
                  @click="addEditingTask"
                  style="float: right"
                  type="primary"
                  plain
              >
                添加此任务
              </el-button>
            </div>
          </el-header>
          <el-main style="height: 78vh">
            <div style="margin: 10px 0;">
              <el-card style="margin-bottom: 5px" v-for="(item,index) in editingTaskList" :body-style="{padding: '10px'}">
                <div slot="header">
                  <span>{{item.name}}</span>
                  <el-button
                    style="float: right; padding: 3px 0;color: #ff6b81"
                    type="text"
                    icon="el-icon-delete"
                    circle
                    @click="deleteEditingTask(index)"
                  >
                    删除
                  </el-button>
                </div>
                <component
                    style="margin-bottom: 10px;"
                    :key="item.viewRouter + index"
                    :params=item.param
                    :ref="item.viewRouter + index"
                    v-if="!isNull(item.viewRouter)"
                    :is="taskComponentMap[item.viewRouter]"
                >
                </component>
              </el-card>
            </div>
          </el-main>
        </el-container>

      </el-drawer>
    </div>


  </div>
</template>

<script>
import message from "@/utils/message";
import service, {isNull, isValidJSONString, copy} from "@/utils/service"

export default {
  name: "taskTemplate",
  data() {
    return {
      page: {
        loading: true,
        current: 1,
        size: 10,
        pages: 1,
        total: 0,
        data:[],
        lookMe: true,
        name: "",
        adId: "",
      },
      // 编辑模板抽屉开关
      drawer: false,
      taskComponentMap: {
        'views/robotOffice/task/am-ztc-yh': () => import('@/views/robotOffice/task/am-ztc-yh.vue'),
        'views/robotOffice/task/sycm-search-goodKey': () => import('@/views/robotOffice/task/sycm-search-goodKey.vue'),
        'views/robotOffice/task/sycm/competingGoodKey': () => import('@/views/robotOffice/task/sycm/competingGoodKey.vue'),
        'views/robotOffice/task/sycm/industryGoodKey': () => import('@/views/robotOffice/task/sycm/industryGoodKey.vue'),
        'views/robotOffice/task/sycm/findMarketRank': () => import('@/views/robotOffice/task/sycm/findMarketRank.vue'),
        'views/robotOffice/task/operationAid/industryGoodKey': () => import('@/views/robotOffice/task/operationAid/industryGoodKey.vue'),
        'views/robotOffice/task/sycm/trafficSource': () => import('@/views/robotOffice/task/sycm/trafficSource.vue'),
        'views/robotOffice/task/sycm/store/taoBaoDailyData' : () => import("@/views/robotOffice/task/sycm/store/taoBaoDailyData.vue"),
        'views/robotOffice/task/sycm/store/pddDailyData' : () => import("@/views/robotOffice/task/sycm/store/pddDailyData.vue"),
        'views/robotOffice/task/sycm/competitorProduct' : () => import("@/views/robotOffice/task/sycm/competitorProduct.vue"),
        'views/robotOffice/task/sycm/productDetails' : () => import("@/views/robotOffice/task/sycm/productDetails.vue"),
      },
      service: service,
      /* 选中模板 ID */
      sTemplateId: "",
      /* 选中模板名称 */
      sTemplateName: '',
      /* 机器任务列表 */
      robotTaskList: [],
      /* 机器模板列表 */
      /* 表格加载 */
      tabLoading: true,
      /* 选中的任务ID */
      sTaskId: "",
      /* 编辑中的任务列表 */
      editingTaskList: [],
    }
  },
  methods: {
    isNull: isNull,
    /* 获取机器任务列表 */
    getRobotTaskList() {
      let _t = this;
      this.$request.post({
        url: "baseAdmin/robot/taskList",
        success: (res) => {
          _t.robotTaskList = res.map(e => {
            let d = copy(e);
            if (isNull(d.dataForm)) {
              return e
            }
            if (!isValidJSONString(e.dataForm)) {
              message.warning("解析任务 " + e.name + " json 表单时失败")
              return e
            }
            d.dataForm = JSON.parse(e.dataForm)
            d.param = {}
            d.dataForm.forEach(e => {
              d.param[e.field] = isNull(e.defaultValue) ? undefined : e.defaultValue;
            })
            return d
          })
        },
        error: () => {
          message.warning("获取机器任务列表失败")
        },
        allError: (res) => {
          message.warning("获取机器任务列表失败")
        }
      })
    },
    pageChange(v){
      this.page.size = v;
      this.getPage()
    },
    currentChange(v){
      this.page.current = v
      this.getPage()
    },
    /* 分页 */
    getPage(){
      let _t = this;
      _t.page.loading = true;
      this.$request.post({
        url: "robot/taskTemplate/page",
        params: {
          pageNo: _t.page.current,
          pageSize: _t.page.size,
          lookMe: _t.page.lookMe,
          name: _t.page.name,
          adId: isNull(_t.page.adId) ? undefined : _t.page.adId
        },
        success: (res) => {
          _t.page.pages = res.pages
          _t.page.total = res.total
          _t.page.data = res.list
        },
        allError: (err) => {
          console.log(err)
        },
        finally: () => {
          _t.page.loading = false;
        }
      })
    },
    /* 清空分页条件 */
    clearPageConditions(){
      this.page.name = ""
      this.getPage()
    },
    /* 添加选中任务至编辑任务列表 */
    addEditingTask() {
      let _t = this;
      if (isNull(this.sTaskId)) {
        message.warning("请选择任务")
        return;
      }
      let item = this.robotTaskList.find(e => {
        return e.id === _t.sTaskId;
      })
      if (isNull(item)) {
        message.warning("错误!缓存列表中没有该任务")
        return;
      }
      this.editingTaskList.push(copy(item))
    },

    /* 模板列表添加至编辑模板 */
    templateAddToEditTask(item) {
      this.editingTaskList = []
      this.sTemplateName = item.name
      this.sTemplateId = item.id
      // 得到任务快照
      let taskList = JSON.parse(item.taskConfigSnapshot);
      let tempRobotTaskList = copy(this.robotTaskList);
      // 根据 任务 id 将任务快照中的参数值 赋值给新的 任务编辑模板
      taskList.forEach((e) => {
        // 找到当前任务快照对应的任务
        let index = tempRobotTaskList.findIndex(e2 => {
          return e.taskId.toString() === e2.id.toString();
        })
        // 如果存在这个任务就将
        if (index !== -1) {
          tempRobotTaskList[index].param = e.param;
          this.editingTaskList.push(Object.assign({}, tempRobotTaskList[index]))
        }
      })
    },

    /* 删除编辑中的任务 */
    deleteEditingTask(index) {
      this.editingTaskList.splice(index, 1)
    },

    /* 清空操作模板 */
    emptyEditingTask() {
      this.sTemplateName = '';
      this.sTemplateId = '';
      this.editingTaskList = [];
    },

    /* 提交模板*/
    commitTemplate() {
      let _t = this;
      if (!this.checkTemplateParam()) {
        return;
      }
      let data = {
        templateId: isNull(_t.sTemplateId) ? undefined : _t.sTemplateId,
        templateName: _t.sTemplateName,
        taskConfigSnapshot: JSON.stringify(
            _t.editingTaskList.map((e, index) => {
              if (isNull(e.viewRouter)) {
                return {
                  taskId: e.id,
                  taskName: e.name,
                  param: e.param,
                  dataForm: e.dataForm,
                };
              } else {
                return {
                  taskId: e.id,
                  taskName: e.name,
                  param: _t.$refs[e.viewRouter + index][0].getParam(),
                };
              }

            })
        )
      }
      let loading = this.$loading({
        lock: true,
        text: '提交中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$request.post({
        url: "robot/taskTemplate/commit",
        params: data,
        success: (res) => {
          message.success("提交任务模板成功")
          _t.getPage()
        },
        finally: () => {
          loading.close();
        }
      })
    },

    /* 删除模板 */
    removeTemplate(id) {
      if (isNull(id)) {
        message.error("该数据丢失,请刷新重试或联系管理员")
        return;
      }
      let _t = this;
      let loading = this.$loading({
        lock: true,
        text: '提交中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$request.post({
        url: "robot/taskTemplate/delete",
        params: {templateId: id},
        success: (res) => {
          console.log("superAdmin/robot/delete/taskTemplate: ", res)
          _t.getPage();
        },
        finally: () => {
          loading.close();
        }
      })
    },

    /* 校验模板参数 */
    checkTemplateParam() {
      let _t = this;
      if (isNull(_t.sTemplateName)) {
        message.error("请填写模板名称")
        return false;
      }
      if (_t.editingTaskList.length === 0) {
        message.error("请添加需要执行的任务")
        return false;
      }
      for (let i = 0; i < _t.editingTaskList.length; i++) {
        let e = _t.editingTaskList[i];
        if (isNull(e.viewRouter)) {
          for (let element2 of e.dataForm) {
            let e2 = element2;
            if (!e2.nullable && isNull(e.param[e2.field])) {
              message.error("请填写任务 " + e.name + " 参数 : " + e2.label)
              return false;
            }
          }
        } else {
          if (!isNull(_t.$refs[e.viewRouter + i][0].checkParam)) {
            return _t.$refs[e.viewRouter + i][0].checkParam()
          }
        }
      }
      return true;
    },

    /* 打开复制任务模板对话框 */
    openCopyTaskTemplateDiaLog(targetTemplate) {
      let _t = this;
      console.log(targetTemplate)
      this.$prompt('输入新的模板名称', '复制模板',
          {
            confirmButtonText: '确定', cancelButtonText: '取消', closeOnClickModal: false,
            inputPattern: /^.{2,255}$/,
            inputErrorMessage: '新的模板名称长度 (2~255) 个字符',
            inputType: 'textarea'
          })
          .then(({value}) => {
            _t.copyTaskTemplate(targetTemplate.id, value)
          }).catch(() => {})
    },
    copyTaskTemplate(oldTemplateId, newTemplateName) {
      let _t = this;
      let loading = this.$loading({
        lock: true,
        text: '提交中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$request.post({
        url: "robot/taskTemplate/copy",
        params: {oldTemplateId: oldTemplateId, newTemplateName: newTemplateName},
        success: (res) => {
          message.success("复制成功")
          _t.getPage()
        },
        finally: () => {
          loading.close();
        }
      })
    }
  },
  mounted() {
    this.getRobotTaskList();
    this.getPage()
  }
}
</script>

<style scoped>
.descriptions_label {
  font-size: 20px !important;
}
.label {
  font-size: 15px;
  font-weight: bold;
  margin-right: 10px;
}
/deep/.el-card__header{
  padding: 10px 10px;
}
</style>